<template>
  <div style="display: flex; flex-direction: column;">
    <!-- <el-upload
      class="avatar-uploader"
      action=""
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img
        v-if="imageUrl"
        :src="imageUrl"
        class="avatar"
      />
      <el-icon
        v-else
        class="avatar-uploader-icon"
      >
        <Plus />
      </el-icon>
    </el-upload> -->
    <el-upload
      :limit="1"
      list-type="picture-card"
      ref="upload"
      action=""
      :http-request="handleUploadAvatar"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :auto-upload="false"
      :on-change="handlerChange"
    >
      <img
        style="width: 100px;"
        v-if="imageUrl"
        :src="imageUrl"
      />
      <el-icon v-else>
        <Plus />
      </el-icon>
    </el-upload>
    <el-button
      style="margin: 10px 0; width: 75px;"
      @click="handlerUpload"
    >保存</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: "",
    };
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    
    handleUploadAvatar(file) {
      this.$emit("uploadAvatarSubmit", file);
    },
    handlerUpload() {
      this.$refs.upload.submit();
    },
    handlerChange(file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
  },
};
</script>

<style scoped>
.img {
  width: 300px;
  height: 300px;
  background-color: #f9f9f9;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #e9eaec;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>